package com.atguigu.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Permission;
import com.atguigu.entity.Role;
import com.atguigu.service.PermissionService;
import com.atguigu.service.RoleService;
import com.base.BaseController;
import com.github.pagehelper.PageInfo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.MidiDevice;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {
    @Reference
    private RoleService roleService;
    @Reference
    private PermissionService permissionService;

    /*@RequestMapping
    public String index(Model model){
        List<Role> list = roleService.findAll();
        model.addAttribute("list",list);
        return "role/index";
    }*/

    @PreAuthorize("hasAuthority('role.show')")
    @RequestMapping
    public String index(Model model, HttpServletRequest request){
        Map<String, Object> filters = getFilters(request);
        PageInfo<Role> pageInfo = roleService.findPage(filters);
        model.addAttribute("page",pageInfo);
        model.addAttribute("filters",filters);
        return "role/index";
    }

    @PreAuthorize("hasAuthority('role.create')")
    @RequestMapping("create")
    public String create(){
        return "role/create";
    }

    @PostMapping("save")
    public String save(Role role){
        roleService.insert(role);
        return "common/successPage";
    }

    @PreAuthorize("hasAuthority('role.edit')")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id,Model model){
        Role role = roleService.getById(id);
        model.addAttribute("role",role);
        return "role/edit";
    }


    @PostMapping("/update")
    public String update(Role role){
        roleService.update(role);
        return "common/successPage";
    }


    @PreAuthorize("hasAuthority('role.delete')")
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id,Model model){
        roleService.delete(id);
        return "redirect:/role";
    }

    @PreAuthorize("hasAuthority('role.assgin')")
    @GetMapping("assignShow/{roleId}")
    public String assignShow(@PathVariable Long roleId,Model model){
        List<Map<String,Object>> zNodes = permissionService.findPermissionsByRoleId(roleId);
        model.addAttribute("zNodes",zNodes);
        model.addAttribute("roleId",roleId);
        return "role/assignShow";
    }

    @PostMapping("assignPermission")
    public String assignPermission(@RequestParam Long roleId,@RequestParam Long [] permissionIds){
        permissionService.saveRolePermissionRealtionShip(roleId,permissionIds);
        return "common/successPage";
    }
}
